package command
{
	import business.BabyDelegate;
	
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	
	import event.LoadBabyEvent;
	import event.LoadWhoDataEvent;
	
	import model.BabyChartModelLocator;
	
	import mx.containers.TitleWindow;
	import mx.managers.PopUpManager;
	import mx.rpc.IResponder;
	import mx.rpc.events.ResultEvent;
	
	import view.LoadDataPopup;
	
	import vo.Baby;
	
	public class LoadBabyCommand implements IResponder, ICommand
	{
		private var babyChartModel:BabyChartModelLocator = BabyChartModelLocator.getInstance();
		private var titleWindow:TitleWindow;
		
		public function result(data:Object):void
		{
			var resultEvent:ResultEvent = ResultEvent(data);
			var xml:XML = XML(resultEvent.message.body);
			if (xml.failed > 0) {
				(LoadDataPopup(titleWindow)).note.text = "Baby doesn't exist with the input! Please try again.";
				(LoadDataPopup(titleWindow)).note.setStyle("color", "#ff0000");
			} else { 
				var baby:Baby = new Baby(xml);
				if (titleWindow != null) {
					PopUpManager.removePopUp(titleWindow);
				}
				babyChartModel.baby = baby;
				var chartType:String = babyChartModel.getChartType();
				if (babyChartModel.getList(chartType) == null) {
					CairngormEventDispatcher.getInstance().dispatchEvent(new LoadWhoDataEvent(chartType));
				}
			}
		}

		public function execute(event:CairngormEvent):void
		{
			var realEvent:LoadBabyEvent = LoadBabyEvent(event);
			titleWindow = realEvent.titleWindow;	
			new BabyDelegate(this).loadBabyData(realEvent.firstname, realEvent.lastname, realEvent.dob, realEvent.password);
		}
		
		public function fault(info:Object):void {
			
		}
	}
}